<template>
  <div>
    <!-- 提示条 -->
    <el-alert :title="title" type="success" show-icon />
    <!-- 选择区 -->
    <el-row class="data_top">
      <el-col>
        <span>选择商品分类:</span>
        <!-- 选择商品分类级连框  mlgb官网没有,从小网站上嫖到的-->
        <!-- https://www.w3cschool.cn/vue_elementplus/ElementPlusCascader.html -->
        <el-cascader
          v-model="value"
          :options="shuju.object"
          :props="shijian"
          @change="handleChange"
        ></el-cascader>
      </el-col>
    </el-row>
    <!-- tab标签 -->
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" :disabled="but" @click="dialogVisible = true"
          >添加属性</el-button
        >
        <!-- 动态属性 -->
        <el-table :data="dong" border v-if="dong.lenght !== 0">
          <el-table-column :type="off_on">
            <template #default="scope" v-slot="{ row }">
              <!-- 遍历 -->
              <el-tag
                v-for="(tag, i) in scope.row.attr_vals"
                :key="i"
                class="mx-1"
                closable
                @close="hand(i, scope.row)"
              >
                {{ tag }}
              </el-tag>
              <!-- tab输入框 -->
              <el-input
                v-if="scope.row.inputVisible"
                ref="InputRef"
                v-model="scope.row.inputValue"
                class="ml-1 w-20"
                size="small"
                @keyup.enter="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              />
              <!-- 点击添加或隐藏 -->
              <el-button
                v-else
                class="button-new-tag ml-1"
                size="small"
                @click="showInput(scope.row)"
              >
                + New Tag
              </el-button>
            </template>
          </el-table-column>
          <!-- 索引lie -->
          <el-table-column type="index"> </el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope" v-slot="{ row }">
              <el-row>
                <el-button
                  size="small"
                  type="primary"
                  :icon="Edit"
                  @click="tiao('编辑', scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  :icon="Delete"
                  @click="tiao('删除', scope.row)"
                  >删除</el-button
                >
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" :disabled="but" @click="dialogVisible = true"
          >添加参数</el-button
        >
        <!-- 静态表格 -->
        <el-table :data="jing" border v-if="jing.lenght !== 0">
          <el-table-column :type="off_on">
            <template #default="scope" v-slot="{ row }">
              <!-- 遍历 -->
              <el-tag
                v-for="(tag, i) in scope.row.attr_vals"
                :key="i"
                class="mx-1"
                closable
                @close="hand(i, scope.row)"
              >
                {{ tag }}
              </el-tag>
              <!-- tab输入框 -->
              <el-input
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                class="ml-1 w-20"
                size="small"
                @keyup.enter="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              />
              <!-- 点击添加或隐藏 -->
              <el-button
                v-else
                class="button-new-tag ml-1"
                size="small"
                @click="showInput(scope.row)"
              >
                + New Tag
              </el-button>
            </template>
          </el-table-column>
          <!-- 索引lie -->
          <el-table-column type="index"> </el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope" v-slot="{ row }">
              <el-row>
                <el-button
                  size="small"
                  type="primary"
                  :icon="Edit"
                  @click="tiao('编辑', scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  :icon="Delete"
                  @click="tiao('删除', scope.row)"
                  >删除</el-button
                >
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="xie + tishi"
      width="30%"
      :before-close="handleClose"
    >
      <!-- 表单 -->
      <el-form
        ref="formRef"
        :model="numberValidateForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          :label="tishi"
          prop="age"
          :rules="[
            { required: true, message: 'age is required' },
            { type: 'string', message: 'age must be a number' },
          ]"
        >
          <el-input
            v-model.number="numberValidateForm.age"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(formRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, reactive, onMounted, watch, computed } from 'vue';
import { apis } from '@/http/api';
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import type { TabsPaneContext } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue';

import { ElInput } from 'element-plus';
const InputRef = ref<InstanceType<typeof ElInput>>();
const title = ref('注意: 只允许为三级分类设置属性!!!');
//控制闭合
const expand = () => {
  console.log(123);
};
const off_on = ref('expand');
const showInput = (val: any) => {
  val.inputVisible = true;
  off_on.value = 'slot';
};

const handleInputConfirm = (val: any) => {
  if (val.inputValue.trim().length == 0) {
    val.inputVisible = false;
    val.inputValue = '';
    return;
  }
  val.attr_vals.push(val.inputValue.trim());
  val.inputValue = '';
  val.inputVisible = false;
  console.log(val);
  xbt(val);

  console.log('没啥用');
};
const xbt = (val: any) => {
  apis
    .putliebiao(
      ids.value,
      val.attr_id,
      val.attr_name,
      activeName.value,
      val.attr_vals.join(',')
    )
    .then((data) => {
      // jing.value = data.data;
      console.log('222', data);
    });
};
//小标签
const hand = (id: number, val: any) => {
  val.attr_vals.splice(id, 1);
  xbt(val);
};
//表单验证
const formRef = ref<FormInstance>();
//表单名称
const numberValidateForm = reactive({
  age: '',
});
//选择添加还是编辑
const xuanze = ref(0);
//动态标题
const xie = ref('添加');
//商品数据
const shuju = reactive({
  object: null as any,
});
//请求参数的选项
const cool = reactive({
  type: 3,
  // pagenum: 1,
  // pagesize: 5,
});
//总数据条数
const toto = ref(0);
//配置选择器的配置对象
let shijian = {
  value: 'cat_id',
  label: 'cat_name',
  children: 'children',
};
//双向绑定事件
const value = ref([]);
const activeName = ref('many');
//点击数据
const handleChange = () => {
  if (value.value.length !== 3) {
    value.value = [];
    ElMessage.error('分类必须为三级!!!');
    dong.value = [];
    jing.value = [];

    return;
  }

  // console.log(value.value);
};

//判断按钮是否启用
const but = ref(true);
//获取选择第三级的id
const ids = ref(0);
//属性id
const uid = ref(0);
// tab标签页点击事件
const handleClick = (tab: TabsPaneContext, event: Event) => {};
//动态数据
const dong = ref([]) as any;
const jing = ref([]) as any;
//获取数据
const huoqu = () => {
  apis.getcategories(cool).then((data) => {
    if (data.meta.status !== 200) {
      return console.log('获取失败', data);
    }
    shuju.object = data.data;
    toto.value = data.data.total;
    // console.log('数据', data.data);
  });
};
//获取列表数据
const list = (val: string) => {
  apis.getfeilei(ids.value, val).then((data) => {
    if (data.meta.status !== 200) {
      console.log('获取失败');
    } else {
      data.data.forEach((item: any) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : ['new'];
        // item.attr_vals = item.attr_vals.split(' ');
        //控制文本显示隐藏
        item.inputVisible = false;
        //文本输入
        item.inputValue = '';
      });
      // console.log('看这里', data.data);
      if (val == 'many') {
        dong.value = data.data;
        tishi.value = '动态属性';

        console.log('动态');
      } else {
        jing.value = data.data;
        tishi.value = '静态属性';
        console.log('静态');
      }
    }
  });
};
//弹出框
const dialogVisible = ref(false);
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
//动态名称
const tishi = ref('动态属性');

//确认并认证
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      dialogVisible.value = false;
      if (xuanze.value == 0) {
        if (activeName.value == 'many') {
          apis
            .getpost(ids.value, numberValidateForm.age, activeName.value)
            .then((data) => {
              // dong.value = data.data;
              console.log('---', data.data);
            });
        } else {
          apis
            .getpost(ids.value, numberValidateForm.age, activeName.value)
            .then((data) => {
              // jing.value = data.data;
              console.log('222', data);
            });
        }
      } else {
        apis
          .putliebiao(
            ids.value,
            uid.value,
            numberValidateForm.age,
            activeName.value
          )
          .then((data) => {
            console.log('kanzhe1', data);
          });
      }

      list(activeName.value);
      numberValidateForm.age = '';
    } else {
      console.log('error submit!');
      return false;
    }
  });
};
//清空
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  dialogVisible.value = false;
  formEl.resetFields();
};
//编辑删除
//编辑或删除
const tiao = (val: string, lis?: any) => {
  if (lis == undefined) {
    return;
  }
  var a = JSON.parse(JSON.stringify(lis));
  uid.value = a.attr_id;
  console.log(a);
  xie.value = val;
  if (val == '编辑') {
    dialogVisible.value = true;
    // apis.getchaxun(ids.value).then((data) => {
    //   // mingcheng.value = data.data.cat_name;
    //   console.log('编辑', data);
    // });
    apis.getchaid(ids.value, a.attr_id, activeName.value).then((data) => {
      numberValidateForm.age = data.data.attr_name;
      console.log('编辑', data);
    });
    xuanze.value = 1;
  } else {
    console.log('删除');
    // apis.delliebiaos(ids.value).then((data) => {
    //   console.log(data);
    //   list(activeName.value);
    // });
    apis.delcslb(ids.value, a.attr_id).then((data) => {
      console.log(data);
      list(activeName.value);
    });
  }
};

//初始化数据
onMounted(() => {
  huoqu();
});
//事件监听
watch(value, (newName, oldName) => {
  if (newName.length == 0) {
    but.value = true;
  } else if (newName.length == 3) {
    ids.value = value.value[2];
    list(activeName.value);
    but.value = false;
  } else {
    but.value = false;
  }
});
watch(activeName, (name, oldName) => {
  console.log('监听', name);
  if (name == 'many') {
    let a = 'many';
    list(a);
  } else {
    let b = 'only';
    list(b);
  }
});
</script>

<style lang="less" scoped>
.el-alert {
  margin: 20px 0 0;
}
.el-alert:first-child {
  margin: 0;
}
.data_top {
  margin: 15px;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
.el-table {
  margin: 10px;
}
.ml-1,
.w-20 {
  width: 120px;
}
</style>
